/*
 * Copyright 2011 es-planning Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.arctos.ursus.extension.net;

import java.io.IOException;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Queue;

import jp.arctos.ursus.extension.net.exception.ConnectionClosedByPeerException;

/**
 * Socket session.
 * <p>
 * Handles TCP transmission.
 * </p>
 */
class SocketSession extends Session {

    /** Socket channel. */
    SocketChannel channel;

    /** Session writer. */
    SocketSessionWriter writer;

    /** Received data context. */
    ReceivedContext receivedContext;

    /** Session handler. */
    SocketSessionHandler sessionHandler;

    /** Session configuration. */
    SessionConfig config;

    /**
     * Constructor.
     * 
     * @param service Service
     * @param channel Channel
     * @param selectorHandler Selector handler
     * @param config Configuration
     * @throws IOException
     */
    SocketSession(Service service, SocketChannel channel, SelectorHandler selectorHandler, SessionConfig config) throws IOException {
        super(service, selectorHandler);

        this.channel = channel;
        this.config = config;

        sessionHandler = new SocketSessionHandler(this);
        writer = new SocketSessionWriter();
        writer.initQueue(config.getSendQueueSize());
        receivedContext = new ReceivedContext();
        receivedContext.setBuffer(ByteBuffer.allocate(config.getReceivedContextBufferSize()));
    }

    /**
     * {@inheritDoc}
     * 
     */
    @Override
    void doClose() throws IOException {
    	try {
            writer.stopWrite();
            channel.close();
    	} finally {
            selectorHandler.cancel(channel);
            service.sessionClosed(this);
    	}
    }

    /**
     * Get the session handler for this session.
     * 
     * @return Session handler
     */
    SocketSessionHandler getSessionHandler() {
        return sessionHandler;
    }

    /**
     * Receive data from channel.
     * <p>
     * One instance is reused for returning received data context, so it is valid until the next call.
     * </p>
     * 
     * @return Received data context
     * @throws IOException
     */
    ReceivedContext read() throws IOException {
        ByteBuffer buffer = receivedContext.getBuffer();
        buffer.clear();

        int size = channel.read(buffer);
        if (size < 0) {
            // Connection has already disconnected by remote host.
            throw new ConnectionClosedByPeerException();
        }
        buffer.flip();

        receivedContext.setLocalAddress(channel.socket().getLocalSocketAddress());
        receivedContext.setRemoteAddress(channel.socket().getRemoteSocketAddress());

        return receivedContext;
    }

    /**
     * Get send request queue.
     * 
     * @return Send request queue
     */
    Queue<SendRequest> getWriteQueue() {
        return writer.getQueue();
    }

    /**
     * Accept send requests.
     * 
     * @param request Send request data
     * @return "true" if accepted, "false" if unable to be accepted
     */
    boolean send(SendRequest request) {
        if (isClosed()) {
            throw new IllegalStateException();
        }

        return writer.write(selectorHandler, channel, request);
    }

    /**
     * Write send request to channel.
     * 
     * @return Send request data that has been successfully sent
     * @throws Exception
     */
    SendRequest write() throws Exception {
        return writer.onWritable(selectorHandler, channel);
    }

    /**
     * {@inheritDoc}
     * 
     */
    @Override
    SocketAddress getLocalAddress() {
        return channel.socket().getLocalSocketAddress();
    }

    /**
     * Get address of connected remote host.
     * 
     * @return Remote host address
     */
    SocketAddress getRemoteAddress() {
        return channel.socket().getRemoteSocketAddress();
    }

    /**
     * Get value of SO_RCVBUF socket option.
     * 
     * @return SO_RCVBUF Socket option
     * @throws SocketException 
     * @see java.net.Socket#getReceiveBufferSize()
     */
    int getReceiveBufferSize() throws SocketException {
        return channel.socket().getReceiveBufferSize();
    }

    /**
     * Get value of SO_REUSEADDR socket option.
     * 
     * @return SO_REUSEADDR Socket option
     * @throws SocketException 
     * @see java.net.Socket#getReuseAddress()
     */
    boolean getReuseAddress() throws SocketException {
        return channel.socket().getReuseAddress();
    }

    /**
     * Get value of SO_TIMEOUT socket option.
     * 
     * @return SO_TIMEOUT Socket option
     * @throws SocketException 
     * @see java.net.Socket#getSoTimeout()
     */
    int getSoTimeout() throws SocketException {
        return channel.socket().getSoTimeout();
    }

    /**
     * Configure SO_TIMEOUT socket option.
     * 
     * @param timeout SO_TIMEOUT Socket option
     * @throws SocketException 
     * @see java.net.Socket#setSoTimeout(int)
     */
    void setSoTimeout(int timeout) throws SocketException {
        channel.socket().setSoTimeout(timeout);
    }

    /**
     * Get value of SO_KEEPALIVE socket option.
     * 
     * @return SO_KEEPALIVE Socket option
     * @throws SocketException 
     * @see java.net.Socket#getKeepAlive()
     */
    boolean getKeepAlive() throws SocketException {
        return channel.socket().getKeepAlive();
    }

    /**
     * Configure SO_KEEPALIVE socket option.
     * 
     * @param keepAlive SO_KEEPALIVE Socket option
     * @throws SocketException 
     * @see java.net.Socket#setKeepAlive(boolean)
     */
    void setKeepAlive(boolean keepAlive) throws SocketException {
        channel.socket().setKeepAlive(keepAlive);
    }

    /**
     * Get value of SO_SNDBUF socket option.
     * 
     * @return SO_SNDBUF Socket option
     * @throws SocketException 
     * @see java.net.Socket#getSendBufferSize()
     */
    int getSendBufferSize() throws SocketException {
        return channel.socket().getSendBufferSize();
    }

    /**
     * Configure SO_SNDBUF socket option.
     * 
     * @param size SO_SNDBUF Socket option
     * @throws SocketException 
     * @see java.net.Socket#setSendBufferSize(int)
     */
    void setSendBufferSize(int size) throws SocketException {
        channel.socket().setSendBufferSize(size);
    }

    /**
     * Get value of traffic class.
     * 
     * @return Traffic class
     * @throws SocketException 
     * @see java.net.Socket#getTrafficClass()
     */
    int getTrafficClass() throws SocketException {
        return channel.socket().getTrafficClass();
    }

    /**
     * Configure traffic class.
     * 
     * @param trafficClass Traffic class
     * @throws SocketException
     * @see java.net.Socket#setTrafficClass(int)
     */
    void setTrafficClass(int trafficClass) throws SocketException {
        channel.socket().setTrafficClass(trafficClass);
    }

    /**
     * Get value of SO_LINGER socket option.
     * 
     * @return SO_LINGER Socket option
     * @throws SocketException 
     * @see java.net.Socket#getSoLinger()
     */
    int getSoLinger() throws SocketException {
        return channel.socket().getSoLinger();
    }

    /**
     * Configure SO_LINGER socket option.
     * 
     * @param on Valid / Invalid
     * @param linger SO_LINGER Socket option
     * @throws SocketException 
     * @see java.net.Socket#setSoLinger(boolean, int)
     */
    void setSoLinger(boolean on, int linger) throws SocketException {
        channel.socket().setSoLinger(on, linger);
    }

    /**
     * Get value of TCP_NODELAY socket option
     * 
     * @return TCP_NODELAY Socket option
     * @throws SocketException 
     * @see java.net.Socket#getTcpNoDelay()
     */
    boolean getTcpNoDelay() throws SocketException {
        return channel.socket().getTcpNoDelay();
    }

    /**
     * Configure TCP_NODELAY socket option.
     * 
     * @param tcpNoDelay TCP_NODELAY Socket option
     * @throws SocketException
     * @see java.net.Socket#setTcpNoDelay(boolean)
     */
    void setTcpNoDelay(boolean tcpNoDelay) throws SocketException {
        channel.socket().setTcpNoDelay(tcpNoDelay);
    }
}
